from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .ser import *
from meiduo01.models import *


# Create your views here.

class Home(APIView):
    def get(self, request):
        # 获取一级分类
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list1 = []
        for i in cates:
            dict1 = {}
            dict1['id']=i.id
            dict1['name']=i.name
            #获取二级
            two = i.subs.all()#反查询
            twolist = []
            for j in two:
                twodict = {}
                twodict['id'] = j.id
                twodict['name'] = j.name
                three = j.subs.all()
                ser = CateSer(three,many=True)
                twodict['subs'] = ser.data
                twolist.append(twodict)
            dict1['subs'] = twolist
            list1.append(dict1)
            # 查询一级分类，一级下面的二级，一级下面的三级，一级下面所有的商品
        categoods = []
        for j in cates:
            dict = {}
            dict['id'] = j.id
            dict['name'] = j.name
            dict['pic'] = str(j.pic)
            two = j.subs.all()
            twoser = CateSer(two,many=True)
            dict['two'] = twoser.data
            three = Category.objects.filter(top_parent=j.id,level=3).all()
            threeser = CateSer(three,many=True)
            dict['three'] = threeser.data
            # 获取商品,排序，新品按时间倒序排，价格，销量
            sorted = request.GET.get('sorted')#点那个排序那个
            topid = request.GET.get('topid')#顶级id
            goods = Goods.objects.filter(category1_id=j.id,home_show=1).all()
            if sorted:
                if int(topid) == int(j.id):
                    goods = Goods.objects.filter(category1_id=j.id,home_show=1).order_by('-'+sorted).all()
            gser = GoodSer(goods,many=True)
            dict['goods'] = gser.data
            categoods.append(dict)
        return Response({"code":200,"catelist":list1,"categoods":categoods})